package cn.elves.model.rule.service.engine;

import cn.elves.model.rule.entity.constant.NodeTypeConstants;
import cn.elves.model.rule.entity.dto.RuleTreeDTO;
import cn.elves.model.rule.entity.dto.RuleTreeNodeDTO;
import cn.elves.model.rule.service.rules.RuleFilter;
import org.apache.catalina.startup.EngineConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @description: 规则引擎基础类
 */
public class BaseEngine extends EngineConfig implements EngineFilter {

    private Logger logger = LoggerFactory.getLogger(BaseEngine.class);

    @Resource
    private EngineRulesHolder engineRulesHolder;

    @Override
    public DecisionResult process(Long treeId, Map<String, Object> decisionMatter) {
        throw new RuntimeException("未实现规则引擎服务");
    }

    protected RuleTreeNodeDTO engineDecisionMaker(RuleTreeDTO treeRule, Map<String, Object> decisionMatter) {
        RuleTreeNodeDTO ruleTreeNodeDTO = treeRule.getRootNode();
        while (NodeTypeConstants.STEM.equals(ruleTreeNodeDTO.getNodeType())) {
            String ruleKey = ruleTreeNodeDTO.getRuleKey();
            RuleFilter ruleFilter = engineRulesHolder.selectRule(ruleKey);
            String matterValue = ruleFilter.matterValue(decisionMatter);

            ruleTreeNodeDTO = ruleFilter.filter(matterValue, ruleTreeNodeDTO.getRuleTreeNodeLineDTO());
            logger.info("决策树引擎=>{} treeId：{} treeNode：{} ruleKey：{} matterValue：{}", treeRule.getTreeName(), ruleTreeNodeDTO.getTreeId(), ruleTreeNodeDTO.getId(), ruleKey, matterValue);
        }

        return ruleTreeNodeDTO;
    }

}
